<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="UTF-8">
    <title>我的实时聊天</title>
    <script type="text/javascript" src="./../../head.js"></script>
<body>
<div class="container">
    <div class="form-horizontal">
        <div class="form-group">
            <label for="chat_content" class="col-sm-10">聊天室</label>
        </div>
        <div class="form-group">
            <div class="col-sm-10">
                <textarea id="chat_content" disabled class="form-control" rows="16"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label for="user_name" class="col-sm-1 control-label">用户:</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="user_name" value="" name="userName"/>
            </div>
            <div class="col-sm-4">
                <button id="btn_join" class="btn btn-primary">加入聊天室</button>
                <button id="btn_exit" class="btn btn-danger">退出聊天室</button>
            </div>
        </div>
        <div class="form-group">
            <label for="send_text" class="col-sm-1 control-label">消息:</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="send_text" value="" name="sendText"/>
            </div>
            <div class="col-sm-4">
                <button id="btn_send" class="btn btn-success">发送</button>
                <button id="btn_clear" class="btn btn-primary">清空消息</button>
            </div>
        </div>
    </div>
</div>
</body>
</head></html>
<script>
    $(function () {
        $('<audio id="chatAudio">' +
            '<source src="./../../audio/notify.ogg" type="audio/ogg"> ' +
            '<source src="./../../audio/notify.mp3" type="audio/mpeg">' +
            '<source src="./../../audio/notify.wav" type="audio/wav"> ' +
            '</audio>').appendTo('body');//载入声音文件

        var prefixUrl = 'ws://wqxyl.5166.info/jzpz/chatRoom/';
        /**
         * WebSocket连接对象
         */
        var ws;

        //判断当前浏览器是否支持WebSocket
        if (!('WebSocket' in window)) {
            alert('Not support websocket');
        } else {
            $('#btn_join').click(function () {
                var userName = $('#user_name').val();
                //创建WebSocket连接对象
                ws = new WebSocket(prefixUrl + userName);
                //连接成功建立的回调方法
                ws.onopen = function (event) {
                    console.log('建立连接');
                };
                //接收到消息的回调方法
                ws.onmessage = function (event) {
                    $('#chat_content').append(event.data + '\n');
                    var scrollTop = $("#chat_content")[0].scrollHeight;
                    //调整滚动条
                    $("#chat_content").animate({"scrollTop": $('#chat_content')[0].scrollHeight}, "slow");
                    $('#chatAudio')[0].play(); //播放声音
                };
                //连接发生错误的回调方法
                ws.onerror = function (event) {
                    console.log('发生错误');
                };
                //连接关闭的回调方法
                ws.onclose = function (event) {
                    console.log('关闭连接');
                }
            });

            //发送消息
            function sendMessage() {
                var value = $('#send_text').val();
                if (value.length != 0) {
                    ws.send(value);
                    $('#send_text').val('');
                }

            }

            //关闭连接
            function closeWebSocket() {
                if (ws) {
                    ws.close();
                }
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                if (ws) {
                    ws.close();
                }
            };
            $("#send_text").keydown(function (e) {
                var curKey = e.which;
                if (curKey == 13) {
                    sendMessage();
                }
            });

            //发送消息
            $('#btn_send').click(function () {
                sendMessage();
            });
            //点击退出聊天室
            $('#btn_exit').click(function () {
                closeWebSocket();
            });
            //清空消息
            $('#btn_clear').click(function () {
                $('#chat_content').text('');
            });
        }
    });
</script>